package com.neu.controller;

import com.neu.base.AuthContants;
import com.neu.base.Result;
import com.neu.entity.DTO.RegisterForm;
import com.neu.entity.User;
import com.neu.entity.security.LoginUser;
import com.neu.service.AuthenticationService;
import com.neu.utils.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;


@Tag(name = "登录注册")
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    RedisUtil redisUtil;


    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result login(@RequestBody User user) {
        //要经过两层过滤器，第一个是验证token 第二个是验证用户密码
        LoginUser loginUser = authenticationService.login(user.getUsername());
        return Result.success(loginUser);
    }

    @GetMapping("/loginUser")
    @Operation(summary = "获取当前登录的用户信息")
    public Result getLoginUser() {
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return Result.success(user);
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody RegisterForm registerForm) {

        return authenticationService.register(registerForm);
    }

    @PostMapping("/captcha")
    @Operation(summary = "模拟发送验证码")
    public Result sendCaptcha(@RequestBody RegisterForm registerForm) {
        String username = registerForm.getUsername();
        String captcha = String.valueOf((int) ((Math.random() * 9 + 1) * 100000)); // 6位数字验证码
        redisUtil.set(AuthContants.REDIS_KEY_AUTH_CAPTCHA + username, captcha, 60 * 5); // 5分钟有效
        return Result.success(captcha);
    }
}